﻿package com.foxhis.webstart.download;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Map.Entry;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.border.LineBorder;

import com.foxhis.webstart.gui.StartMain;

/**
 * 下载Panel
 * 
 * @author nestor
 * 
 *         2009-7-22 上午11:47:18
 */
public class DownloadPanel extends JPanel  implements DownloadListen {

	private static final long serialVersionUID = 1L;

	private Download download; // 当前下载对象

	public JProgressBar progressBar;

	public String lastIP_N;

	public String u;

	private List<Download> downloadList = new ArrayList<Download>();

	public StartMain applet;

	public String mainFile;// 执行主程序名称

	//private Preferences pre;

	// private String vesion = "vesion_" + lastIP_N;

	//public HashMap<String,String> versionList;
	public HashMap<String,String> downurls;//Darke
	public final static int treadNum=3;//Darke
	public final static String ERROR="Error: ";
	
	private File file;
	private DownloadPanel donlop;
	private String selectDown[] = new String[] {"help.jar"};// 选择性下的文件
	private long countvalue=0;
	private boolean showprocess=true;
	private Color mycolor=new Color(194, 204, 198);
	private String rmiport="9070";
	private String hjndiport=null;
	public String systemname="Pms";
	public String errorMessage="";
	public String downloadpath="";
	private int errortype=0;
	public boolean nocompare=false;
	private boolean haswriteversion=false;
	public SimpleDateFormat spd_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private Properties versionProperties=new Properties();
	private Properties wversionP=new Properties();
	private Properties tversionP=new Properties();
	private Properties comversionP=new Properties();
	private boolean showfirst=false;
	private boolean isenable=true;
	private String errorUrl="";
	private String training;
	private boolean iscluster=false;
	private String params=null;
	private CountDownLatch runlatch=new CountDownLatch(1);
	private boolean hasparam=false;
	private boolean isLAN=false;
	private boolean lansame=true;
	
	/*private String getElementValue(String keyvalue,String defaultvalue,Element elem){
		String result=defaultvalue;
		if(elem.getElementsByTagName(keyvalue).getLength()!=0){
			if(elem.getElementsByTagName(keyvalue).item(0).getFirstChild()!=null){
				result=elem.getElementsByTagName(keyvalue).item(0).getFirstChild().getNodeValue();
				if(result.isEmpty()){
					result=defaultvalue;
				}
			}
		}
		return result;
	}
	private String getDocValue(String keyvalue,String defaultvalue,Document elem){
		String result=defaultvalue;
		if(elem.getElementsByTagName(keyvalue).getLength()!=0){
			if(elem.getElementsByTagName(keyvalue).item(0).getFirstChild()!=null){
				result=elem.getElementsByTagName(keyvalue).item(0).getFirstChild().getNodeValue();
				if(result.isEmpty()){
					result=defaultvalue;
				}
			}
		}
		return result;
	}*/
	private String getSpliValue(String[] split,String defaultvalue){
		if(split.length>1){
			return split[1];
		}
		else{
			return "";
		}
	}
	
	private String readxml(){
		long inittime=System.currentTimeMillis();
		String content = applet.serverxml;
		System.out.println("Server:"+content);
		String homeurl=downloadpath+"/"+systemname+"/";
		downurls=new HashMap<String, String>();
		String temcolor="194, 204, 198";
		boolean hasmain=false;
		if(!content.isEmpty()){
			try {
				String split[]=content.split(";");
				for(String temp:split){
					if(!temp.isEmpty()){
						if(temp.startsWith("rmiport")){
							rmiport=getSpliValue(temp.split("="),rmiport);
						}
						else if(temp.startsWith("systemname")){
							systemname=getSpliValue(temp.split("="),systemname);
						}
						else if(temp.startsWith("download-path")){
							downloadpath=getSpliValue(temp.split("="),downloadpath);
						}
						else if(temp.startsWith("color")){
							temcolor=getSpliValue(temp.split("="),temcolor);
						}
						else if(temp.startsWith("JMSPort")){
							hjndiport=getSpliValue(temp.split("="),hjndiport);
						}
						else if(temp.startsWith("MainFile")){
							applet.mainName=getSpliValue(temp.split("="),applet.mainName);
							applet.mainName=applet.mainName.replace(".exe", "");
						}
						else if(temp.startsWith("training")){
							training=getSpliValue(temp.split("="),training);
						}
						else if(temp.startsWith("cluster")){
							iscluster=Boolean.parseBoolean(getSpliValue(temp.split("="),"false"));
						}
					}
				}
				System.out.println("Versions:"+applet.versionxml);
				System.out.println("MainName:"+applet.mainName);
				 if(applet.versionxml.contains(applet.mainName)&&!applet.mainName.isEmpty()){
						mainFile=applet.mainName+".exe";
						applet.mainName=applet.mainName.substring(0,1).toUpperCase()+applet.mainName.substring(1).toLowerCase();
						hasmain=true;
				}
				File filepath=new File(downloadpath);
				if(downloadpath.isEmpty()){
					errortype=1;
					downloadpath=getProgramurl();
				}
				else if((!filepath.isAbsolute())||((!filepath.exists())&&(!filepath.mkdirs()))){
					errortype=2;
					errorUrl=downloadpath;
					System.out.println("ErrorURL:"+errorUrl);
					downloadpath=getProgramurl();
				}
				
				systemname=systemname.substring(0,1).toUpperCase()+systemname.substring(1).toLowerCase();
				homeurl=downloadpath+"/"+systemname+"/";
				try{
					temcolor=temcolor.replace(" ", "");
					String reds=temcolor.split(",")[0];
					String greens=temcolor.split(",")[1];
					String blues=temcolor.split(",")[2];
					int redi=Integer.parseInt(reds.trim());
					int greeni=Integer.parseInt(greens.trim());
					int bluei=Integer.parseInt(blues.trim());
					mycolor=new Color(redi,greeni,bluei);
					applet.setBackground(mycolor);
					setBackground(mycolor);
					setOpaque(true);
					progressBar.setBackground(mycolor);
					System.out.println("Color:"+temcolor);
				}catch(Exception k){
					System.out.println("Default Color!");
					log(k.getMessage(),ERROR);
					k.printStackTrace();
				}
			} catch (Exception e) {
				log(e.getMessage(),ERROR);
				e.printStackTrace();
			}
		}
		if(!hasmain){
			showMessageDialog(applet,"服务器无法找到运行文件"+applet.serverName.toLowerCase()+".exe",
					applet.serverName+" System", JOptionPane.ERROR_MESSAGE);
			return null;
		}
		homeurl=homeurl.replace("\\", "/");
		System.out.println("GetXMLMessageTime-----"+(System.currentTimeMillis()-inittime));
		return homeurl;
	}
	private void init() {
		this.donlop=this;
		this.isenable=true;
		this.nocompare=false;
		this.lansame=true;
		this.versionProperties=new Properties();
		this.wversionP=new Properties();
		this.showprocess=true;
		this.errorMessage="";
		progressBar.setVisible(true);
		errortype=0;
		showfirst=false;
		haswriteversion=false;
		downloadList = new ArrayList<Download>();
		String homeurl=readxml();
		long inittime=System.currentTimeMillis();
		u = homeurl;//程序路径//Darke
		lastIP_N = applet.ip.substring(applet.ip.lastIndexOf(".") + 1);
		file = new File(u + "downlog.log");
		showfirst=!file.exists();
		System.out.println("Path exists:"+!showfirst);
		if(homeurl==null||!checkPermission()){
			closeDownload();
		}
		
		try {
			file=file.getCanonicalFile();
		} catch (IOException e) {
			u = homeurl+"/"+systemname+"/";//程序路径//Darke
			file = new File(u + "downlog.log");
		}
		downurls.put(mainFile, u);
		System.out.println("Home:"+u);
		Date date=new Date();
		log("\n\n--------------------------------"+spd_time.format(date)+"--------------------------------\n\n","");
		System.out.println("MainFile:" + mainFile);
		if(applet.islogin&&!applet.isSinfornia){
			return;
		}
		String content=applet.versionxml;
		File versionfile=new File(u+"version.ini");
		if(versionfile.exists()){
			haswriteversion=true;
			try {
				InputStream is = null;
				is = new FileInputStream(versionfile);
				versionProperties.load(is);
				is.close();
			} catch (Exception e) {
				log(e.getMessage(),ERROR+"Init load Versions--");
				e.printStackTrace();
			}
		}
			String[] versionsplit=content.split(",");
			boolean ismain=false;
			String surl=((!(applet.hotelurl==null||applet.hotelurl.isEmpty()))?applet.hotelurl:applet.serverurl);
			isLAN=!(applet.hotelurl==null||applet.hotelurl.isEmpty());
			System.out.println(isLAN+":"+applet.hotelurl);
//			if(isLAN){
//				try {
//					File lanversionfile=new File(applet.hotelurl+"version.ini");
//					if(lanversionfile.exists()){
//						InputStream is = null;
//						is = new FileInputStream(lanversionfile);
//						comversionP.load(is);
//						is.close();
//					}
//				} catch (Exception e) {
//					log(e.getMessage(),ERROR+"Init load Versions--");
//					e.printStackTrace();
//				}
//			}
			for(String temp:versionsplit){
				if(!temp.isEmpty()){
					String[] fileversion=temp.split("=");
					String name=fileversion[0];
					String versionstr =fileversion[1];
					if(versionstr.contains("[")){
						downurls.put(name, versionstr.substring(versionstr.indexOf("[")+1));
						versionstr=versionstr.substring(0,versionstr.indexOf("["));
					}
				
					wversionP.put(name,versionstr);
					String url_ =  surl+getFolder(1,name)+name;
					if (name.equalsIgnoreCase(mainFile)) {
						name = name.replace(".exe", "系统");
						name=name.substring(0,1).toUpperCase()+name.substring(1);
						url_ = surl+ mainFile;
						ismain=true;
					}
					
					Download download1 = new Download(url_,versionstr,donlop,isLAN);
					download1.setDownloadName(name);
					if(ismain){
						downloadList.add(0, download1);
						ismain=false;
					}
					else{
						downloadList.add(download1);
					}
					
				}
			}
			if(versionProperties.equals(wversionP)){
				nocompare=true;
				System.out.println("No Update!");
			}
			setInitDatas();
			System.out.println("DownloadInitTime-----"+(System.currentTimeMillis()-inittime));
	}

	/**
	 * 清除临时文件
	 */
	public void deletetempFile(File dir){
		File[] filelist=dir.listFiles();
		for(int i=0;i<filelist.length;i++){
			if(filelist[i].isDirectory()){
				deletetempFile(filelist[i]);
			}
			else{
				String filename=filelist[i].getName();
				int index=filename.indexOf(".");
				if(index>-1){
					filename=filename.substring(index);
					if(filename.contains("_")){
						filelist[i].delete();
					}
				}
			}
		}
	}
	
	public static String getProgramurl(){
		Process pp;
		String result=System.getProperty("user.home").substring(0,2)+"/Program Files";
		try {
			pp = Runtime.getRuntime().exec("cmd /c echo %programfiles%");
			InputStream in=pp.getInputStream() ;
			String tem="";
			BufferedReader rd=new BufferedReader(new InputStreamReader(in));
			if((tem=rd.readLine())!=null){
				result=tem;
			}
			rd.close();
			pp.getOutputStream().close();
			in.close();
			pp.getErrorStream().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return result;
	}
	/**
	 * 判断是否是管理员
	 */
	public boolean isSuper(){
		Process pp;
		try {
			pp = Runtime.getRuntime().exec("net localgroup administrators");
			InputStream in=pp.getInputStream() ;
			String tem="";
			BufferedReader rd=new BufferedReader(new InputStreamReader(in));
			while((tem=rd.readLine())!=null){
				if(tem.equalsIgnoreCase(System.getProperty("user.name"))){
					rd.close();
					return checkPermission();
				}
			}
			rd.close();
			in.close();
		} catch (IOException e) {
			log(e.getMessage(),ERROR);
			showMessageDialog(applet,"系统错误！"+e.getMessage(),applet.serverName+" System", JOptionPane.ERROR_MESSAGE);
			return false;
		}
		showMessageDialog(applet,"无权限运行"+applet.serverName+"系统！",applet.serverName+" System", JOptionPane.ERROR_MESSAGE);
		setVisible(false);
		return false;
	}
	
	public void closeDownload(){
		long inittime=System.currentTimeMillis();
		applet.actionJS("setHide()");
		System.gc();
		isenable=false;
		System.out.println("CloseTime-----"+(System.currentTimeMillis()-inittime));
//		applet.setEnabled(false);
/*		applet.setEnabled(false);
		applet.validate();
		applet.destroy();
		applet.stop();*/
		//System.exit(0);
	}
	
	/**
	 * 主程序是否正在运行
	 */
	public void checkRun(){
		Process pp;
		try {
			//pp = Runtime.getRuntime().exec("tasklist");
			pp = Runtime.getRuntime().exec("cmd /C wmic process get executablepath /VALUE");
			InputStream in=pp.getInputStream() ;
			String tem="";
			BufferedReader rd=new BufferedReader(new InputStreamReader(in));
			pp.getOutputStream().close();
			while((tem=rd.readLine())!=null){
				if(!tem.isEmpty()&&tem.endsWith(u.replace("/", "\\")+mainFile)){
					rd.close();
					in.close();
					showMessageDialog(applet,""+applet.serverName+"系统正在运行！请关闭进程后重新打开！",applet.serverName+" System", JOptionPane.DEFAULT_OPTION);
//					setVisible(false);
					closeDownload();
					return;
				}
			}
			rd.close();
			in.close();
			//if(checkPermission()){
			return;
			//}
		} catch (IOException e) {
			log(e.getMessage(),ERROR+"CheckRun--");
			showMessageDialog(applet,"获取进程失败！"+e.getMessage(),applet.serverName+" System", JOptionPane.DEFAULT_OPTION);
		}
		closeDownload();
	}
	
	/**
	 * 用户是否有权限读写主目录
	 */
	public boolean checkPermission(){
		/*FilePermission maindir=new FilePermission(u,"read,write");
		SecurityManager sysm=System.getSecurityManager();
		Object context = null;
		if (sysm != null) {
			   context = sysm.getSecurityContext(); 
			   try{
				   sysm.checkPermission(maindir,context);
				   FileWriter fileWriter = new FileWriter(file, true);
				   fileWriter.close();
				   return true;
			   }catch(Exception e){
				   e.printStackTrace();
			   }
		}*/
		 try{
			 	if(!file.exists()){
					file.getParentFile().mkdirs();
					file.createNewFile();
				}
			 	File tempfile=new File(u + "start_temp");
			 	tempfile.createNewFile();
				FileReader fileread=new FileReader(tempfile);
				fileread.read();
				fileread.close();
				FileWriter fileWriter = new FileWriter(tempfile, true);
				fileWriter.write("temp");
				fileWriter.close();
				tempfile.delete();
				return true;
		   }catch(Exception e){
			   log(e.getMessage(),ERROR+"CheckPermission--");
			   e.printStackTrace();
		   }
		showMessageDialog(applet,"您没有读写主目录的权限！",applet.serverName+" System", JOptionPane.DEFAULT_OPTION);
		return false;
	}
	/**
	 * 获取下载目录
	 */
	public String getFolder(int mode,String filename){
		String resultname=filename.replace(" ","").toLowerCase();
		return (resultname.endsWith(".properties"))?((mode==1)?"Properties/":""):
			(resultname.endsWith(".jar"))?("lib/"):("");
	}
	/**
	 * 生成目录
	 */
	public String createDirectory(String directory){
		File filed = new File(directory);
		if(!filed.exists())
			filed.mkdirs();
		if (filed.isFile()){
			String home=directory.contains(":")?directory:((!(u.contains(":")||directory.contains(":")))?(u+directory):directory);//程序路径//Darke
			File dr= new File(home);
			if(!dr.exists())
				dr.mkdirs();
			return home;
		}
		return directory;
	}
	/**
	 * 根据文件名获取下载路径
	 */
	public String getFileUrl(String name){
		String urls=downurls.get(name);
		if(urls!=null){
			if(!urls.isEmpty()){
				String fileoper=urls.contains("\\")?"\\":"/";
				if(!urls.endsWith(fileoper))
					urls=urls+fileoper;
				return urls+name;
			}
		}
		urls=u+getFolder(0,name);
		createDirectory(urls);
		return (urls+name);
	}
	/*public String getFileUrl(String name){
		for(int i=0;i<jarList.length;i++){
			String filename=jarList[i];
			String urlstr=(filename.contains("(")&&filename.contains(")"))?
					(filename.substring(filename.lastIndexOf("(")+1,filename.lastIndexOf(")"))):u;
			String fileoper="/";
			if(urlstr!=null){
				fileoper=urlstr.contains("\\")?"\\":"/";
				if(!urlstr.endsWith(fileoper))
					urlstr=urlstr+fileoper;
			}
			filename=filename.substring(filename.indexOf("=")+1,(filename.contains("("))?
					filename.lastIndexOf("("):filename.length());
			if(filename.trim().equals(name.trim())){
				if((!filename.equals(mainFile))&&(!jarList[i].contains("("))){
					File filed = new File(u+getFolder(0,name));
					if (!filed.exists())
						filed.mkdirs();
					return (u+getFolder(0,name)+name);
				}
				for(int j=0;j<downurls.length;j++){
					if((urlstr!=null)&&(downurls[j]!=null)){
						if(urlstr.trim().equals(downurls[j].trim())&&(!downurls[j].trim().equals(fileoper))){
							urlstr=(urlstr.contains(":")?urlstr:((u.contains(":"))?(u+urlstr):urlstr));
							File tem=new File(urlstr+name);
							try {
								return tem.getCanonicalPath();
							} catch (IOException e) {
								return u+getFolder(0,name)+name;
							}
						}

					}
				}
			}
		}
		return u+name;
	}*/
	/*--------------------E (Darke 2012.01.31)--------------------*/
	public void downFile() {
		// if (downloadList.size() == 0)// 已经下载了新文件
		// writeVersion();

		// File file = new File(u + "Pastoral.exe");
		// // File file2 = new File(u + "fat.exe");
		// System.out.println(compareVersion() + " " + file.exists());
		// boolean sameVersion = compareVersion();
		//
		// if (sameVersion && file.exists()) {// 版本相同&文件存在
		// System.out.println("Run...");
		// runEXE();
		// } else if (downloadList.size() != 0) {
		// file.deleteOnExit();
		// download = (Download) downloadList.remove(0);
		// System.out.println("Download...");
		// download.download(this);
		// }

		// for (Download download : downloadList) {
		// this.download = (Download) downloadList.remove(0);
		// if (checkRun(download.getDownloadName().replace("载入", ""))) {
		// System.out.println(download.getDownloadName() + "下载..." +
		// downloadList.size());
		// download.download(this);
		// } else
		// runEXE();
		// }
		// System.out.println("DOWNSIZE:" + downloadList.size());
		
		if (downloadList.size() == 0||nocompare||(applet.islogin&&!applet.isSinfornia))// 已经下载了新文件
			runEXE();
		else {
			this.download = (Download) downloadList.remove(0);
			if (checkRun(download.getDownloadName().replace("载入", ""))) {
				System.out.println(download.getDownloadName() + "下载..." + downloadList.size());
				if(showprocess&&applet!=null){
					if(!isenable){
						return;
					}
					applet.actionJS("showApplet()");
			/*		applet.setBackground(mycolor);
					setBackground(mycolor);
					progressBar.setBackground(mycolor);*/
					showprocess=false;
				}
				/*new Thread(){
					public void run() {*/
						try {
							download.initFile();
						} catch (Exception e1) {
							log(e1.getMessage(),ERROR+"DownThread initFile--");
							e1.printStackTrace();
						}
						long current=System.currentTimeMillis();
						ExecutorService exc=Executors.newCachedThreadPool();
						CountDownLatch latch;
						int contenlent=download.getContentLength();
						long treadlenth=contenlent;
						String downurl=download.getUrl();
						boolean lantarget=false;
						boolean dlan=download.getLAN();
						if(dlan&&contenlent>0){
							latch=new CountDownLatch(1);
							long endpos=contenlent;
							long[] startpos=new long[1];
							startpos=download.setBreakPoint(startpos,1,treadlenth);
							download.setMutiple(0,latch,startpos[0],endpos,treadlenth);
							exc.execute(download);
							lantarget=true;
						}
						else{
							if(dlan){
								download.setLAN(false);
								try {
									downurl=downurl.replace(applet.hotelurl, applet.serverurl);
									download.initURL(downurl);
								} catch (MalformedURLException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								contenlent=download.getContentLength();
							}
							long[] startpos=new long[treadNum];
							long endpos=0;
							treadlenth=contenlent/treadNum;
							startpos=download.setBreakPoint(startpos,treadNum,treadlenth);
							latch=new CountDownLatch(treadNum);
							for(int i=0;i<treadNum;i++){
								startpos[i]+=treadlenth*i;
								if(i==treadNum-1){
									endpos=contenlent;
								}else{
									endpos=treadlenth*(i+1)-1;
								}
								Download multiple=new Download(downurl,download.getVersion(),donlop,false);
								multiple.setMutiple(i,latch,startpos[i],endpos,treadlenth);
								exc.execute(multiple);
							}
							lantarget=false;
						}
						try{
							latch.await();
							exc.shutdown();
							if(!errorMessage.isEmpty()){
								boolean ismain=download.getFileName().equalsIgnoreCase(mainFile);
								showMessageDialog(applet,errorMessage,
												applet.serverName+" System", JOptionPane.ERROR_MESSAGE);
								log(errorMessage,ERROR);
								download.closeFile();
								if(ismain||download.beclose){
									closeDownload();
								}
								errorMessage="";
							
							}
							else{
								boolean issuecd=download.setTargetFile(lantarget?1:treadNum,treadlenth);
								if(!issuecd){
									if (showConfirmDialog(applet, "下载文件"+download.getFileName()+"错误！是否继续?",
											applet.serverName+" System", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION){
										closeDownload();
									}
								}
								else{
									copyFile();
									System.out.println(download.getFileName()+"--"+(System.currentTimeMillis()-current));
									log(download.getFileName()+"\t\t\t\t\t:"+(System.currentTimeMillis()-current),"");
									tversionP.put(download.getFileName(), download.getVersion());
									if((!nocompare)){
										File versionfile=new File(u+"version.ini");
										FileWriter fw=new FileWriter(versionfile);
										tversionP.store(fw, "");
										//fw.write(applet.versionxml);
										fw.flush();
										fw.close();
									}
								}
							}
							downFile();
						}catch(Exception e){
							log(e.getMessage(),ERROR+"DownThread DownLoad--");
							e.printStackTrace();
						}
						
					/*};
				}.start();*/
			}
			else{
				copyFile();
				downFile();
			}
			//downFile();
			/*if (checkRun(download.getDownloadName().replace("载入", ""))) {
				System.out.println(download.getDownloadName() + "下载..." + downloadList.size());
				try {
				download.download(this);
				}catch (Exception e) {
					e.printStackTrace();
				}finally {
					
				}
			} else
				downFile();*/
		}
	}
	
	private void copyFile(final String copyfile,final String todirectory){
		new Thread(new Runnable() {
			@Override
			public void run() {
				File tofile=new File(todirectory);
				if(!tofile.exists()){
					tofile.mkdirs();
				}
				String cmdstr="cmd /c call copy /Y \""+copyfile+"\" \""+todirectory+"\"";
				System.out.println(cmdstr);
				try {
					Runtime.getRuntime().exec(cmdstr);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
		lansame=false;
	}
	
	private void copyFile(){
		if(isLAN){
			String fileName=download.getFileName();
			String sversion=wversionP.getProperty(fileName);
			String lanversion=comversionP.getProperty(fileName);
			if(!download.getLAN()||!sversion.equals(lanversion)){
				copyFile(getFileUrl(fileName).replace("/", "\\"), applet.hotelurl+getFolder(0,fileName).replace("/", "\\"));
				lansame=false;
			}
		}
	}
	
	public void showMessageDialog(Component parentComponent, Object message, String title, int messageType){
		//applet.actionJS("setHide()");
		JOptionPane.showMessageDialog(null, message, title, messageType);
		//applet.actionJS("showApplet()");
	}
	
	public int showConfirmDialog(Component parentComponent, Object message, String title, int optionType){
		//applet.actionJS("setHide()");
		int result = JOptionPane.showConfirmDialog(null, message,title,optionType);
		showprocess=true;
//		applet.actionJS("showApplet()");
		return result;
	}

	/**
	 * 检查每个JAR是否存在和版本是否正确
	 * 
	 * @nestor
	 * 
	 * @2009-7-22 下午03:52:05
	 * 
	 */
	private boolean checkRun(String fileName) {// 返回True则下载此文件
		String file = fileName.replace("系统", ".exe");
		if (file.equalsIgnoreCase(mainFile)) {
//			file = new File(u + mainFile);
			if(showfirst&&errortype!=0){
					switch(errortype){
						case 1:
							if (showConfirmDialog(applet, "没有配置下载目录，是否使用默认目录?",applet.serverName+" System", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION){
								this.file.delete();
								closeDownload();
								return false;
							}
							break;
						case 2:
							if (showConfirmDialog(applet, "<html>配置路径("+errorUrl+")错误，是否使用至默认目录?<br>(注：配置文件中的路径分隔符应设置为 \\\\ 或者 / )</html>",applet.serverName+" System", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION){
								this.file.delete();
								closeDownload();
								return false;
							}
							break;
						default:break;
					}
				}
			errortype=0;
		} else {
			//file = new File(u + "lib\\" + fileName);//Darke
//			file = new File(getFileUrl(fileName));//Darke
		}
		
//		if (!file.exists())// 不存在该文件
//			return true;
//		if(file.length()==0){
//			return true;
//		}
		
		boolean result = checkVersion(file);
		if (result) {// 不同版本文件，则先删除原来的我文件再下载
			for (String name : selectDown){
				if (name.equalsIgnoreCase(fileName)) {
					String versionp=versionProperties.getProperty(file);
					if(versionp!=null){
						if (showConfirmDialog(applet, "你想下载文件(" + fileName + ")吗?",applet.serverName+" System", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION){//Darke
							break;
						}
						else{
							wversionP.setProperty(file, versionp);
							return false;
						}
					}
					else{
						break;
					}
				}
			}
			if(file.toLowerCase().equals(mainFile.toLowerCase())){
				checkRun();
			}
			
			//file.delete();// 找不到直接删除
		}
		return result;
	}

	/**
	 * 检查文件版本
	 * 
	 * @nestor
	 * 
	 * @2009-7-22 下午03:52:05
	 * 
	 */
	private boolean checkVersion(String fileName) {// 返回True则此文件版本和服务器上的不相同
		String version = null;
		String thisversion=null;
//		String name = fileName;
		// if(applet.isCheckVersion.equals("false")&&name.startsWith("Pastoral"))//如果参数为false的主程序，每次都检测下载
		// return false;
		/*for (int i = 0; i < jarList.length; i++) {
			if (jarList[i].indexOf(name) != -1) {
				version = jarList[i].substring(0, jarList[i].indexOf("="));
				break;
			}
		}*/
		version=wversionP.getProperty((fileName.equalsIgnoreCase(mainFile))?mainFile:fileName);
		//version=versionList.get(name);
		thisversion=versionProperties.getProperty((fileName.equalsIgnoreCase(mainFile))?mainFile:fileName);
		boolean result=false;
		if(version==null||thisversion==null){
			result=true;
		}
		else{
			result=(!thisversion.equals(version));
		}
		if(result){
			System.out.println(fileName);
			System.out.println(thisversion+":"+version);
			if(isLAN){
				try {
					File lanversionfile=new File(applet.hotelurl+"version.ini");
					if(lanversionfile.exists()){
						InputStream is = null;
						is = new FileInputStream(lanversionfile);
						comversionP.load(is);
						is.close();
					}
					String lanversion=comversionP.getProperty((fileName.equalsIgnoreCase(mainFile))?mainFile:fileName);
					if(lanversion!=null){
						if(version!=null&&!version.equals(lanversion)){
							download.setLAN(false);
							try {
								download.initURL(applet.serverurl+getFolder(1,fileName)+
										((fileName.equalsIgnoreCase(mainFile))?mainFile:fileName));
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
					}
				} catch (Exception e) {
					log(e.getMessage(),ERROR+"Init load Versions--");
					e.printStackTrace();
				}
			}
			
		}
		/*if(file.length()>0&&(name.toLowerCase().endsWith(".jar")||
				name.toLowerCase().endsWith(".exe"))){//Darke
			try {
				Properties base = new Properties();
				JarFile jarfile=new JarFile(file);
				boolean result =true;
				String readVersion="";
				if(jarfile!=null){
					InputStream intf=jarfile.getInputStream(jarfile.getEntry("META-INF/MANIFEST.MF"));
					base.load(intf);
					readVersion=base.getProperty("Manifest-Version");
					intf.close();
					result=!version.equals(readVersion);
				}
				jarfile.close();
				fileJar = new JarFile(file);
				boolean result = !version.equals(fileJar.getManifest().getMainAttributes().getValue("Manifest-Version"));
				fileJar.close();
				System.out.println(readVersion+":"+version);
				if(result)
				log(name + "\t:\t" + result);
				return result;
			} catch (IOException e) {
				e.printStackTrace();
			}
		--------------------B (Darke)--------------------
		}else{
			String dllver=pre.get(name.toLowerCase(),"1.0");
			boolean result=!version.equalsIgnoreCase(dllver);
			System.out.println(dllver+":"+version);
			if(result)
			log(name + "\t:\t" + result);
			return result;
		}
		--------------------E (Darke)--------------------
		*/
		
		return result;
	}

	public void log(String txt,String type) {
		FileWriter fileWriter;
		try {
			fileWriter = new FileWriter(file, true);
			fileWriter.write(type+txt + "\r\n");
			fileWriter.flush();
			fileWriter.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写入Vesion
	 * 
	 * @nestor
	 * 
	 * @2009-7-22 下午03:52:05
	 * 
	 */
	//private void writeVersion() {
	// pre.put(vesion, this.applet.getVesion());
	//}
	public void writeVersion(String keyname) {
		/*for (int i = 0; i < jarList.length; i++) {
			if (jarList[i].indexOf(keyname) != -1) {
				String versionname = jarList[i].substring(0, jarList[i].indexOf("=")).toLowerCase();
				pre.put(keyname.toLowerCase(), versionname);
				break;
			}
		}*/
		//String versionname = versionList.get(keyname);
		//pre.put(keyname.toLowerCase(), versionname);
	}
	/**
	 * 比较版本号，相同返回TRUE，版本不存在或者不相同返回FALSE
	 * 
	 * @nestor
	 * 
	 * @2009-7-22 下午02:52:21
	 * 
	 * @return
	 */
	// public boolean compareVersion() {
	//
	// if (pre.get(vesion, null) == null)// 没有找到该KEY
	// return false;
	// else
	// return pre.get(vesion, null).equals(this.applet.getVesion()) ? true :
	// false;
	//
	// }
	
	
	public String getHotelHistory(String defaultdata){
		if(!(applet.hotelid==null||applet.hotelid.isEmpty())){
			return applet.hotelid;
		}
		String result=defaultdata;
		if(applet.hotelxml!=null){
			if((!applet.hotelxml.isEmpty())&&applet.hotelxml.contains("/")){
				if(result==null)
					result=applet.hotelxml.substring(0,applet.hotelxml.indexOf("/"));
				else{
					if(result.isEmpty())
					result=applet.hotelxml.substring(0,applet.hotelxml.indexOf("/"));
				}
			}
		}
		System.out.println("HistoryHotel:"+result);
		return result;
	}
	
	public void setInitDatas(){
		new Thread(){
			public void run() {
				long inittime=System.currentTimeMillis();
				hasparam=false;
				Properties base = new Properties();
				try {
					File ini = new File(u + systemname.toLowerCase()+".ini");
					if (!ini.exists())
						ini.createNewFile();
		
					String port = applet.url.substring(applet.url.lastIndexOf(":") + 1);
					InputStream is = null;
					is = new FileInputStream(ini);
					base.load(is);
					is.close();
					String shotelid=getHotelHistory(base.get("HotelID")+"");
					/*boolean issameip=(base.getProperty("IP")!=null)?
							base.getProperty("IP").equals(applet.ip + ":" + rmiport):false;*/
					base.setProperty("IP", applet.ip + ":" + (iscluster?(hjndiport!=null)?hjndiport:rmiport:rmiport));
					if(base.getProperty("WebPort")==null)
						base.setProperty("WebPort", port);
					String allhotelid=base.getProperty("AllHotelID");
					if(allhotelid==null){
						base.setProperty("AllHotelID", applet.hotelxml);
					}
					else /*if(!issameip)*/{
						allhotelid=URLDecoder.decode(allhotelid, "UTF-8");
						System.out.println("本地AllHotelID"+allhotelid);
						if(!applet.hotelxml.equals(allhotelid)){
							Map<String,String> hotelmap=new HashMap<String,String>();
							String sethotel="";
							String[] splitho=allhotelid.split(",");
							for(String temp:splitho){
								String[] splitt=temp.split("/");
								if(!(splitt[0]==null||splitt[0].isEmpty())){
									hotelmap.put(splitt[0],splitt.length>1?splitt[1]:"");
								}
							}
							String[] splitho2=applet.hotelxml.split(",");
							for(String temp:splitho2){
								String[] splitt=temp.split("/");
								if(!(splitt[0]==null || splitt[0].isEmpty())){
									hotelmap.put(splitt[0],splitt.length>1?splitt[1]:"");
								}
							}
							for(Entry<String, String> temp:hotelmap.entrySet()){
								sethotel+=temp.getKey()+"/"+temp.getValue()+",";
							}
							if(!sethotel.isEmpty()){
								sethotel+=",";
								sethotel=sethotel.replace(",,", "");
								base.setProperty("AllHotelID",sethotel);
							}
							
						}
					}
					if(base.getProperty("JMSPort")==null){
						if(hjndiport!=null)
							base.setProperty("JMSPort", hjndiport);
					}
					else{
						if(hjndiport==null){
							base.remove("JMSPort");
						}
						else{
							base.setProperty("JMSPort", hjndiport);
						}
					}
		//			base.setProperty("allhotelid ", applet.hotelxml);
		//			if(base.getProperty("ModelList")==null||!issameip)
					base.setProperty("ModelList", applet.modelxml);
					if(base.getProperty("Language")==null)
						base.setProperty("Language", "Chinese");
					//if(base.getProperty("Model")==null||!issameip)
					if(applet.islogin){
						base.setProperty("Model", applet.modelNum);
					}
		//			if(base.getProperty("HotelID")==null||!issameip)
					base.setProperty("HotelID",shotelid);
					if(!(training==null||training.trim().isEmpty())){
						base.setProperty("Training",training);
					}
					else if(base.getProperty("Training")!=null){
						base.remove("Training");
					}
					FileOutputStream output = new FileOutputStream(ini);
					base.store(output, "");
					output.flush();
					output.close();
					File runbat = new File(u +"run.bat");
					String param="";
					param+=runbat.getParentFile().toURI().getRawPath()+" ";//路径
					if(mainFile.contains("pms")){
						param+=applet.modelNum+" ";//模块号
						param+=applet.modelxml+" ";//模块列表
						param+=URLEncoder.encode(shotelid, "UTF-8");//所选酒店
						if(applet.hotelxml!=null){
							param+=" "+URLEncoder.encode(applet.hotelxml, "UTF-8");//酒店列表
						}
					}
		//			String runstr="cmd /c start "+u.replace(" ", "\" \"")+mainFile+" "+path;
					String wrtitestr=mainFile+" "+param;
					if(!applet.isSinfornia){
						param="";
						param+=runbat.getParentFile().toURI().getRawPath()+" ";//路径
						param+="AUTOLOGIN ";//路径
						param+=applet.ip + ":" + rmiport+" ";//服务器IP和端口
						param+=URLEncoder.encode("/*USERNAME*/"+applet.username, "UTF-8")+" ";//用户名
						param+=URLEncoder.encode("/*PASSWORD*/"+applet.password, "UTF-8")+" ";//密码
						param+=URLEncoder.encode("/*HOTELID*/"+applet.hotelid, "UTF-8")+" ";//酒店ID
						if(applet.language==null||applet.language.isEmpty()){
							JOptionPane.showMessageDialog(null, "请选择语言！", applet.serverName+" System", JOptionPane.ERROR_MESSAGE);
							closeDownload();
							return;
						}
						param+=applet.language+" ";//语言
						param+=applet.modelNum+" ";//模块号
						
					}
					params=param;
					hasparam=true;
					FileWriter fileWriter = new FileWriter(runbat);
					wrtitestr=wrtitestr.replace("%", "%%");
					fileWriter.write(wrtitestr);
					fileWriter.flush();
					fileWriter.close();
				}catch(Exception k){
					k.printStackTrace();
				}
				runlatch.countDown();
				System.out.println("WriteInitTime-----"+(System.currentTimeMillis()-inittime));
			};
		}.start();
	}
	
	public void runEXE() {
		if (downloadList.size() == 0||nocompare||(applet.islogin&&!applet.isSinfornia)) {
			if(!isenable){
				return;
			}
			
			long inittime=System.currentTimeMillis();
			System.out.println("Run...");
//			deletetempFile(new File(u));//Darke

			try {
//				progressBar.setVisible(false);
				validate();
				if(!applet.isSinfornia){
					if(!applet.islogin){
//						applet.actionJS("showLoginDiv()");
						closeDownload();
						return;
					}
				}
				if(!hasparam){
					runlatch.await();
				}
				String runstr="cmd /c call \""+u/*.replace(" ", "\" \"")*/+mainFile+"\""+" "+params;
				//System.out.println(u + mainFile + "#@$");//Darke
				//Runtime.getRuntime().exec(u + mainFile);//Darke
				System.out.println(runstr+ "#@$");
				Process pp=Runtime.getRuntime().exec(runstr);
				InputStream in=pp.getInputStream() ;
				InputStream err=pp.getErrorStream();
				pp.getOutputStream().close();
//				BufferedReader rd=new BufferedReader(new InputStreamReader(err));
//				String tem="";
				in.close();
//				while((tem=rd.readLine())!=null){
//					System.out.println("[RunWarning]------------"+tem);
//					break;
//				}
				err.close();
				try{
					if(((!haswriteversion)||(haswriteversion&&!nocompare))&&(!(applet.islogin&&!applet.isSinfornia))){
							File versionfile=new File(u+"version.ini");
							FileWriter fw=new FileWriter(versionfile);
							wversionP.store(fw, "");
							//fw.write(applet.versionxml);
							fw.flush();
							fw.close();
					}
					if(isLAN&&!lansame){
						File versionfile=new File(applet.hotelurl+"version.ini");
						boolean canwrite=true;
						if(!versionfile.exists()){
							try{
								canwrite=versionfile.createNewFile();
							}catch(Exception k){
								System.out.println("[RunWarning]------------"+k.getMessage());
								canwrite=false;
							}
						}
						if(canwrite){
							FileWriter fw=new FileWriter(versionfile);
							wversionP.store(fw, "");
							//fw.write(applet.versionxml);
							fw.flush();
							fw.close();
						}
					}
				} catch (Exception e) {
					log(e.getMessage(),ERROR+"runEXE write version--");
					e.printStackTrace();
				}
			
				System.out.println("RunTime-----"+(System.currentTimeMillis()-inittime));
//				Runtime.getRuntime().exec(runstr);
				System.out.println("end!");
				//runlog("cmd /c start "+runstr);
				// this.applet.getAppletContext().showDocument(new URL("#"));
				// applet.actionJS("WinClose()");
				// 隐藏进度条
				closeDownload();
				new Thread(){
					public void run() {
						if(!lansame){
							if(comversionP.isEmpty()){
								if(isLAN){
									try {
										File lanversionfile=new File(applet.hotelurl+"version.ini");
										if(lanversionfile.exists()){
											InputStream is = null;
											is = new FileInputStream(lanversionfile);
											comversionP.load(is);
											is.close();
										}
									} catch (Exception e) {
										log(e.getMessage(),ERROR+"Init load Versions--");
										e.printStackTrace();
									}
								}
							}
							if(nocompare&&isLAN&&!wversionP.equals(comversionP)){
								for(Entry<Object, Object> temp:wversionP.entrySet()){
									String filename=temp.getKey()+"";
									if(!temp.getValue().equals(comversionP.get(filename))){
										copyFile(getFileUrl(filename).replace("/", "\\"),applet.hotelurl+getFolder(0,filename).replace("/", "\\"));
									}
								}
							}
						}
					};}.start();
				// this.applet.validate();
				// System.exit(0);

			} catch (Exception e) {
				log(e.getMessage(),ERROR+"runEXE run system--");
				e.printStackTrace();
			}
		}
	}
	
	/*private void runlog(String cmd){
		Process pp;
		try {
			//pp = Runtime.getRuntime().exec("tasklist");
			pp = Runtime.getRuntime().exec(cmd);
			InputStream in=pp.getInputStream() ;
			String tem="";
			BufferedReader rd=new BufferedReader(new InputStreamReader(in));
			pp.getOutputStream().close();
			while((tem=rd.readLine())!=null){
				System.out.println(tem);
			}
			rd.close();
			in.close();
			System.out.println("end!");
			//if(checkPermission()){
			return;
			//}
		} catch (IOException e) {
			showMessageDialog(applet,"运行程序失败！"+e.getMessage(),applet.serverName+" System", JOptionPane.DEFAULT_OPTION);
		}
	}*/

	/**
	 * 通过IP返回主机名称
	 * 
	 * @nestor
	 * 
	 * @2009-8-24 下午04:35:36
	 * 
	 * @param ip
	 * @return
	 */
	private String getHostName(String ip) {
		String hostName = null;
		try {
			InetAddress inet = InetAddress.getByName(ip);
			hostName = inet.getHostName();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hostName;
	}

	public DownloadPanel(StartMain applet) {
		this.setLayout(new BorderLayout());
		this.setBackground(mycolor);
		this.add(getProgressBar(), BorderLayout.CENTER);
		this.applet = applet;
//		downloadFile();
	}
	
	
	public void downloadFile(){
		init();
		if(u!=null){
			this.downFile();
		}
		else{
			closeDownload();
		}
	}

	public JProgressBar getProgressBar() {
		if (progressBar == null) {
			progressBar = new JProgressBar();
			progressBar.setBackground(mycolor);
			progressBar.setString("Waiting...");
			progressBar.setStringPainted(true);
			progressBar.setBorder(new LineBorder(new java.awt.Color(0, 0, 0), 1, false));
			// progressBar.setForeground(new java.awt.Color(255, 128, 64));
			progressBar.setFont(new java.awt.Font("宋体", 1, 12));
		}
		return progressBar;
	}

	public synchronized void updateScreen(long downded) {
		countvalue+=downded;
		download.draw(countvalue);
	}
	
	public void setCountValue(long countvalue){
		this.countvalue=countvalue;
	}
}
